const {
  add,
  del,
  edit,
  search,
  searchBy,
} = require('../js/mysql.js')

const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const jwtAuth = require('../jwtAuth')

router.use(jwtAuth)

router.prefix('/users')

// 登录接口
router.post('/login', async function (ctx, next) {
  let { account, password } = ctx.request.body;
  let user = await searchBy(`account='${account}'`);
  if (user.length === 0) {
    ctx.body = {
      msg: '用户不存在',
      code: 201,
    }
  } else if (user[0].state === 1) {
    if (user[0].account == account && user[0].password == password) {
      let token = jwt.sign({ account, password }, "ikzhj", {
        expiresIn: 60 * 60 * 24
      })
      ctx.body = {
        msg: '登录成功',
        code: 200,
        data: {
          token,
          account,
          permission: user[0].permission,
        }
      }
    } else {
      ctx.body = {
        msg: '账号或密码输入有误',
        code: 201,
      }
    }
  } else {
    ctx.body = {
      msg: '用户被禁用',
      code: 201,
    }
  }

});
// 分页和搜索查询 
router.get('/pagination',async(ctx,next) => {
  const { page=1,limit=3,search= " "} = ctx.request.query;
  let sql = `state='1' and (account LIKE '%${search}%' or name LIKE '%${search}%') order by id DESC LIMIT ${(page-1)*limit},${limit}`;
  let data = await searchBy(sql);
  let sql2 =  `state='1' and (account LIKE '%${search}%' or name LIKE '%${search}%')`;
  let total = await searchBy(sql2);
  ctx.body={
    code:200,
    msg:"操作成功",
    data,
    total: total.length
  }
})
// 查询用户个人信息
router.get('/:account', async (ctx, next) => {
  const { account } = ctx.params;
  let user = await searchBy(`account='${account}'`);
  if(user.length !== 0){
    ctx.body = {
      code: 200,
      msg: "操作成功",
      data: user[0]
    }
  }else{
    ctx.body = {
      code:201,
      msg: "操作失败",
    }
  }
});
// 新增用户
router.post('/',async(ctx,next) => {
  const {account,name,phone} = ctx.request.body;
  let param = [account,name,phone];
  await add(param,`user (account,name,phone) values ('${account}','${name}','${phone}')`);
  ctx.body={
    code:200,
    msg: "操作成功"
  }
});
// 修改个人信息
router.put('/:id', async (ctx, next) => {
  const {id} = ctx.params;
  const {nickName, name, gender,nationality,politicalStatus,education,phone,email,address,imageUrl} = ctx.request.body;
  let param =[nickName, name, gender,nationality,politicalStatus,education,phone,email,address,imageUrl];
  let data = await edit(param,`nick_name='${nickName}',name='${name}',gender='${gender}',nationality='${nationality}',political_status='${politicalStatus}',education='${education}',phone='${phone}',email='${email}',address='${address}',avatar='${imageUrl}' where id=${id}`);
	ctx.body = {
		msg: '操作成功',
		code: 200,
		data
	}
});
// 修改密码
router.put('/change/:account', async(ctx, next) => {
  const {account} = ctx.params;
  const {pass} = ctx.request.body;
  let data = await edit([pass],`password='${pass}' where account='${account}'`);
  ctx.body = {
    msg: '操作成功',
		code: 200,
		data
  }
})
// 修改权限
router.put('/per/:id',async(ctx,next) => {
  const {id} = ctx.params;
  const {permission} = ctx.request.body;
  console.log(permission);
  await edit([permission],`permission='${permission}' where id='${id}'`);
  ctx.body = {
    code:200,
    msg: "操作成功"
  }
})
// 重置密码
router.put('/pass/:id',async(ctx,next) => {
  const {id} = ctx.params;
  await edit([000000],`password='000000' where id='${id}'`);
  ctx.body = {
    code:200,
    msg: "操作成功"
  }
})
// 修改用户信息
router.put('/user/:id', async (ctx, next) => {
  const {id} = ctx.params;
  const {name, gender,nationality,political_status,education,phone,email,address} = ctx.request.body;
  let param =[name, gender,nationality,political_status,education,phone,email,address];
  await edit(param,`name='${name}',gender='${gender}',nationality='${nationality}',political_status='${political_status}',education='${education}',phone='${phone}',email='${email}',address='${address}' where id=${id}`);
	ctx.body = {
		msg: '操作成功',
		code: 200,
	}
});
// 删除用户（假）
router.put('/deluserF/:id',async(ctx,next) => {
  const {id} = ctx.params;
  await edit([0],`state='0' where id='${id}'`);
  ctx.body = {
    code:200,
    msg: "操作成功"
  }
})
// 批量删除（假）
router.put('/delallf/id',async(ctx,next)=>{
  const IDlist = ctx.request.body;
  for(let i in IDlist){
    await edit([0],`state=0 where id='${IDlist[i]}'`);
  };
  ctx.body = {
    code:200,
    msg: "操作成功"
  }
})

module.exports = router
